"""
拉取每日必应图片
"""

import requests
from bs4 import BeautifulSoup
import os
from qiniu_util import upload

from model import Img
import mysql


URL = 'https://dailybing.com/'
TMP_DIR = '../static/tmp'
KEY_PREFIX = 'bing/img'


# 图片下载
def download_image(image_url):
    filename = os.path.basename(image_url)
    # 获取图片
    response = requests.get(image_url)
    if response.status_code == 200:
        file_suffix = response.headers.get('Content-Type').split('/')[1]
        file_path = os.path.join(TMP_DIR, f'{filename}.{file_suffix}')
        # 写入文件
        with open(file_path, 'wb') as file:
            file.write(response.content)
        print(f"图片已保存到{file_path}")
        return file_path
    else:
        print(f"图片下载失败")


# 数据拉取
def pull_data(url):
    response = requests.get(url)
    if response.status_code == 200:
        text = response.text
        soup = BeautifulSoup(text, 'html.parser')
        big_panel_div = soup.find('div', class_='big-panel')
        image_date = big_panel_div.find('div', class_='image-date').text.replace('年', '-').replace('月', '-').replace('日', '')
        image_caption_div = big_panel_div.find('div', class_='image-caption')
        image_title = image_caption_div.find('div', class_='image-title').text
        image_copyright = image_caption_div.find('div', class_='image-copyright').text
        img_elements = big_panel_div.find('div', class_='image-container').findAll('img', class_='img-fluid')
        h_img = ''
        v_img = ''
        for img_element in img_elements:
            img_id = img_element.get('id')
            if img_id == 'big-image-h':
                image_path = download_image(img_element.get('data-src'))
                h_img = generate_img_key(image_path)
                upload(h_img, image_path)
            if img_id == 'big-image-v':
                image_path = download_image(img_element.get('data-src'))
                v_img = generate_img_key(image_path)
                upload(v_img, image_path)
        img = Img(image_date, image_title, image_copyright, h_img, v_img)
        mysql.save_img(img)
    else:
        print('数据拉取失败')


def generate_img_key(img_path):
    return os.path.join(KEY_PREFIX, os.path.basename(img_path)).replace('\\', '/')


if __name__ == '__main__':
    pull_data(URL)

